package com.example.demo.rsa;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.Test;

import java.io.IOException;
import java.io.StringWriter;
import java.security.*;
import java.util.Base64;

/**
 * @description:
 * @author: WangYX
 * @create: 2022-09-11 21:39
 * @Version: 1.0.0
 **/

public class RSAUtils {

    static {
        try {
            Security.addProvider(new BouncyCastleProvider());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test() throws NoSuchProviderException, NoSuchAlgorithmException, IOException {
//        KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA", "BC");
        KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
        keygen.initialize(1024);
        KeyPair pair = keygen.generateKeyPair();

        PrivateKey priv = pair.getPrivate();
        PublicKey pub = pair.getPublic();
        byte[] privBytes = priv.getEncoded();
        byte[] pubBytes = pub.getEncoded();

        byte[] decode = Base64.getEncoder().encode(privBytes);
        String pri = new String(decode);
        byte[] decod1e = Base64.getEncoder().encode(pubBytes);
        String pub1 = new String(decod1e);

        System.out.println();
        System.out.println(pri);
        System.out.println(pub1);
        System.out.println();

        PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes);
        ASN1Encodable encodable = pkInfo.parsePrivateKey();
        ASN1Primitive primitive = encodable.toASN1Primitive();
        byte[] privateKeyPKCS1 = primitive.getEncoded();

        PemObject pemObject = new PemObject("RSA PRIVATE KEY", privateKeyPKCS1);
        StringWriter stringWriter = new StringWriter();
        PemWriter pemWriter = new PemWriter(stringWriter);
        pemWriter.writeObject(pemObject);
        pemWriter.close();

        String pemString = stringWriter.toString();
        System.out.println("私钥为：\r\n" + pemString);


        SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes);
        ASN1Primitive primitive1 = spkInfo.parsePublicKey();
        byte[] publicKeyPKCS1 = primitive1.getEncoded();

        PemObject pemObject1 = new PemObject("PUBLIC KEY", publicKeyPKCS1);
        StringWriter stringWriter1 = new StringWriter();
        PemWriter pemWriter1 = new PemWriter(stringWriter1);
        pemWriter1.writeObject(pemObject1);

        pemWriter1.close();

        String pempubString = stringWriter1.toString();

        System.out.println("公钥为：\r\n" + pempubString);


        //公钥加密


        //私钥解密

    }


}

